import AuthComponent from '@/components/Authorized/AuthComponent';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Button,
  message,
  DatePicker,
  Radio,
  Input,
  Select,
} from 'antd';
import React, { useState, useCallback, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { useRequest } from '@umijs/hooks';
import { getInvoiceInfoPage, downloadinvoiceExcel } from './service';
import moment from 'moment';
import styles from './index.less';
const { Option } = Select;

// let hiddenData = null;
const TableList = (props) => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [exportFlag, handleExportFlag] = useState('')
  const actionRef = useRef();
  const ref = useRef();
  const searchRef = useRef();
  const reloadTable = useCallback(function reloadData() {
    if (searchRef.current) {
      searchRef.current.click();
    }
  }, []);

  const [height, controlH] = useState(300);

  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 360);
    } else {
      controlH(document.body.clientHeight - 470);
    }
  }, [isCollapse])
  const columns = [
    {
      title: '辅营订单号',
      dataIndex: 'orderNo',
      width: 100,
    },
    {
      title: '业务单号',
      dataIndex: 'invoiceNo',
      width: 80,
    },
    {
      title: '开始日期',
      hideInTable: true,
      dataIndex: 'beginDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '结束日期',
      hideInTable: true,
      dataIndex: 'endDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '开票状态',
      key: 'invoiceStatus',
      initialValue: '',
      dataIndex: 'invoiceStatus',
      width: 100,
      filters: [
        {text: '未开票',value: '未开票'},
        {text: '已申请开票', value: '已申请开票'},
        {text: '开票成功', value: '开票成功'},
        {text: '开票失败', value: '开票失败'}
      ],
      valueEnum: {
        '': '全部',
        '0': '未开票',
        '1': '已申请开票',
        '2': '开票成功',
        '3': '开票失败',
      },
    },
    {
      title: '抬头类型',
      key: 'titleType',
      dataIndex: 'titleType',
      width:110,
      filters: [
        {text: '个人', value: '个人'},
        {text: '企业', value: '企业'}
      ],
      valueEnum: {
        '': '全部',
        '1': '个人',
        '0':'企业'
      },
    },
    {
      title: '发票抬头',
      dataIndex: 'invoiceTitle',
      hideInSearch: true,
      width: 80,
    },
    {
      title: '纳税人识别号',
      hideInSearch: true,
      dataIndex: 'taxNo',
      width: 100,
    },
    {
      title: '发票金额（元）',
      hideInSearch: true,
      dataIndex: 'invoicePrice',
      width: 120,
    },
    {
      title: '商品名称',
      hideInSearch: true,
      dataIndex: 'productName',
      width: 80,
    },
    {
      title: '商品单价（元）',
      hideInSearch: true,
      dataIndex: 'productPrice',
      width: 120,
    },
    {
      title: '商品数量',
      hideInSearch: true,
      dataIndex: 'productNumber',
      width: 80,
    },
   
    {
      title: '接收邮箱',
      hideInSearch: true,
      dataIndex: 'email',
      width: 80,
    },
    {
      title: '接收手机',
      hideInSearch: true,
      dataIndex: 'phone',
      width: 80,
    },
    {
      title: '失败原因',
      hideInSearch: true,
      dataIndex: 'causeFailure',
      width: 80,
    },
    {
      title: '开票时间',
      hideInSearch: true,
      dataIndex: 'invoiceTime',
      width: 80,
    },
    {
      title: '提交时间',
      hideInSearch: true,
      dataIndex: 'createTime',
      width: 80,
    },
    {
      title: '信息来源',
      hideInSearch: true,
      dataIndex: 'sourceInformation',
      width: 80,
    },
    {
      title: '操作人',
      hideInSearch: true,
      dataIndex: 'userName',
      width: 80,
    }
  ];
  const [inited, setInited] = useState(false);
  const [firstLoadDate, setFirstLoadDate] = useState(true);
  // const [orderSaleDate, setorderSaleDate] = useState(true)
  useEffect(() => {
    if (actionRef.current && inited) {
       reloadTable();
    } else {
      setInited(true);
    }
  }, [inited]);

    // 切换清空搜索
  //   useEffect(() => {
  //     hiddenData = null
  //   // eslint-disable-next-line react-hooks/exhaustive-deps
  //   }, [])
  // 获取列表详情方法
  const beforeSearchSubmit = useCallback(params => {
    params['beginDate'] = params.beginDate ? params.beginDate.format('YYYY-MM-DD') : '';
    params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';
    if (!isCollapse) {
      return { ...params }
    } else {
      if (event&&event.target&&event.target.querySelector&&event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('beginDate') === -1) {
          params.beginDate = ''
        }
        if (Object.keys(params).indexOf('endDate') === -1) {
          params.endDate = ''
        }
      } else if (event&&event.target&&event.target.querySelector&&event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          beginDate: moment(),
          endDate: moment() 
        })
        // hiddenData = {}
      }
      // return { ...hiddenData, ...params }
      return { ...params }
    }
  }, []);
  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选列
  const [searchParams, handleSearchParams] = useState() // 存储搜索条件
  // 选中添加值
  const tableSelectChange = (selectedRowKeys, selectedRows) => {
    handleSelectedRowKeys(selectedRowKeys);
    handleSelectedRows(selectedRows);
  };
  // 设置选中的值
  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };
  //导出方法
  const handleExport = () => {
    if (!exportFlag){
      message.error('表格数据为空')
      return false
    }
    const hide = message.loading('正在导出');
    let res = downloadinvoiceExcel(searchParams)
      .then(res => {
        let blob = new Blob([res], {
          type:
            'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        let elink = document.createElement('a');
        let time=moment(Date.now()).format('YYYY-MM-DD HH_ss_mm')
        elink.download = '发票信息表'+time+'.xls'
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        hide();
        message.success('导出成功');
      })
      .catch(err => {
        console.log(err);
      });
  };

  return (
    <>
      <ProTable
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        actionRef={actionRef}
        formRef={ref}
        dateFormatter="YYYY-MM-DD"
        scroll={{ x: 1100, y: height }}
        size='small'
        className={`${styles.invoiceinformation} rest-pro-table-form-compact ${isCollapse?'':'collapse'}`}
        search={{
          searchText: (
            <span ref={searchRef} href>
              查询
            </span>
          ),
          onCollapse: val => {
            controlC(val)
            // if (!val && hiddenData) {
            //   ref.current.setFieldsValue({
            //     // beginDate: hiddenData.beginDate,
            //     // endDate: hiddenData.endDate,
            //     invoiceNo:hiddenData.invoiceNo,
            //     titleType: hiddenData.titleType,
            //     invoiceStatus: hiddenData.invoiceStatus,
            //     orderNo: hiddenData.orderNo
            //   })
            // } else {
            //   hiddenData = ref.current.getFieldsValue()
            // }
          },
          span: { //设置排列方式
            xs: 24,
            sm: 24,
            md: 6,
            lg: 6,
            xl: 6,
            xxl: 6,
          }
        }}
        toolBarRender={() => [
           <AuthComponent authCode="mkt.invoiceinformation.export">
           <Button icon="download" type="primary" onClick={handleExport} selectedKeys={[]} style={{ padding: '0px 0px 0px 8px',width:'73px' }}>
            导出           
          </Button>
          </AuthComponent>
        ]}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>发票信息表</span>
          </div>
        }
        beforeSearchSubmit={beforeSearchSubmit}
        request={params => {
          if (!params['beginDate'] && !params['endState']&& firstLoadDate) {
            setFirstLoadDate(false)
            params['beginDate'] = moment().format('YYYY-MM-DD');
            params['endDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              beginDate: moment()
            })
            ref.current.setFieldsValue({
              endDate: moment()
            })
          }
          if (!params['invoiceStatus']) {
            ref.current.setFieldsValue({
              invoiceStatus: ''
            })
          }
          if (!params['titleType']) {
            ref.current.setFieldsValue({
              titleType: ''
            })
          }
          if (!params['orderNo']) {
            ref.current.setFieldsValue({
              orderNo: ''
            })
          }
          if (!params['invoiceNo']) {
            ref.current.setFieldsValue({
              invoiceNo: ''
            })
          }
          handleSearchParams(params);
          return getInvoiceInfoPage(params);
        }}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        onRow={record => {
          return {
            onClick: () => {
            },
          };
        }}
        columns={columns}
        rowKey="id"
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
      />
    </>
  );
};

export default Form.create()(TableList);
